package com.dftdla.mq.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.session.Session;
import com.dftdla.util.Code;
import com.dftdla.utils.RedisKey;
import com.dftdlaRedis.cache.RedisCache;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 14501
 */
@Slf4j
@Configuration
public class RabbitMqConsumer {

    @Resource
    private Session session;
    @Resource
    private RedisCache redisCache;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "msg.single.queue"),
            exchange = @Exchange(name = "msg.topic",type = ExchangeTypes.TOPIC),
            key = "single.#")
    )
    public void listenerSingleMsg(String msg) {
        log.info("接收到分发消息");
        //TODO 分布式锁 -》 消息拉取
        JSONObject json = JSON.parseObject(msg);
        long userId = Long.parseLong(json.get("userId") + "");

        List<Object> list = redisCache.getCacheList(RedisKey.userMsgAutoKey(userId));
        if(list == null){
            return;
        }

        Channel channel = session.getChannel(userId);
        if(channel != null){
            channel.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS.code,list).toString()));
            redisCache.deleteObject(RedisKey.userMsgAutoKey(userId));
        }
    }

}
